package com.itheima.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.User;

import java.util.*;

public class JSONDemo {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        User user1=new User();
        user1.setId(1);
        user1.setUsername("Tom");

        //Convert between List and JSON
        List<User> stuList = new ArrayList<User>();
        stuList.add(user1);
        stuList.add(user1);
        String jsonfromList = null;

        jsonfromList = mapper.writeValueAsString(stuList);
        System.out.println(jsonfromList);

        //List Type is not required here.
        List stuList2 = null;
        try {
            stuList2 = mapper.readValue(jsonfromList, List.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        System.out.println(stuList2);
        System.out.println("************************************");

        //Convert Map to JSON
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userList", stuList);
        map.put("class", "ClassName");
        String jsonfromMap =  mapper.writeValueAsString(map);
        System.out.println(jsonfromMap);

        Map map2 =  mapper.readValue(jsonfromMap, Map.class);
        System.out.println(map2);
        System.out.println(map2.get("studentList"));
        System.out.println("************************************");

        //Convert Array to JSON
        User[] stuArr = {user1, user1};
        String jsonfromArr =  mapper.writeValueAsString(stuArr);
        System.out.println(jsonfromArr);
        User[] stuArr2 =  mapper.readValue(jsonfromArr, User[].class);
        System.out.println(Arrays.toString(stuArr2));
    }
}
